package com.rolfhoward.video.record.ui

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.params.OutputConfiguration
import android.hardware.camera2.params.SessionConfiguration
import android.os.Build
import android.util.Log
import android.util.Size
import android.view.Surface
import android.view.TextureView.SurfaceTextureListener
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.qb.libcommon.activity.BaseActivity
import com.qb.libcommon.utils.ScreenUtils
import com.rolfhoward.video.R
import com.rolfhoward.video.record.camera.CameraCallBack
import com.rolfhoward.video.record.camera.CameraController
import com.rolfhoward.video.record.inner.CameraRatioType
import com.rolfhoward.video.record.manager.VideoEditManager
import com.rolfhoward.video.record.widget.TranslateTouchView
import kotlinx.android.synthetic.main.activity_video_record.*
import kotlin.math.roundToInt


class VideoRecordActivity : BaseActivity(), CameraCallBack, TranslateTouchView.OnTranslateTouchListener {

    private var mStateCallback: CameraDevice.StateCallback? = null
    private var mCameraDevice: CameraDevice? = null
    private var mSurface: Surface? = null
    private var mCaptureSession: CameraCaptureSession? = null
    private var previewSize: Size? = null

    override fun getLayoutId(): Int {
        setStatusBarColor(android.R.color.transparent)
        transparentNavBar()
        return R.layout.activity_video_record
    }

    override fun initView() {
        CameraController.getInstance().setCameraCallback(this)
        initCamera()

        video_preview_touch.setOnTranslateTouchListener(this)
    }

    /**
     * 初始化相机参数
     * */
    private fun initCamera() {
        //设置TextureView预览界面监听
        ttv_video__record_preview.surfaceTextureListener = object : SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
            ) {
                openCamera(width, height)
            }

            override fun onSurfaceTextureSizeChanged(
                    surface: SurfaceTexture,
                    width: Int,
                    height: Int
            ) {

            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
                return true
            }

            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {

            }

        }

        mStateCallback = object : CameraDevice.StateCallback() {
            override fun onOpened(camera: CameraDevice) {
                mCameraDevice = camera
                //开启相机预览
                createCameraPreviewSession()
            }

            override fun onDisconnected(camera: CameraDevice) {
                camera.close()
                mCameraDevice = null
            }

            override fun onError(camera: CameraDevice, error: Int) {
                camera.close()
                mCameraDevice = null
            }

        }
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun openCamera(width: Int, height: Int) {
        var cameraPreviewSizeManager = CameraPreviewSizeManager(this)
        previewSize = cameraPreviewSizeManager.setUpCameraOutputs(
                this,
                width,
                height,
                ttv_video__record_preview
        )
        var texture = ttv_video__record_preview.surfaceTexture
        Log.i("qbwu", "size:${previewSize!!.width},${previewSize!!.height}")
        texture?.setDefaultBufferSize(1080, 1920)
        mSurface = Surface(texture)
        var mCameraManager: CameraManager = getSystemService(CAMERA_SERVICE) as CameraManager
        if (ActivityCompat.checkSelfPermission(
                        this,
                        Manifest.permission.CAMERA
                ) != PackageManager.PERMISSION_GRANTED
        ) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return
        }
        mCameraManager.openCamera("0", mStateCallback!!, null)

    }

    private fun createCameraPreviewSession() {
        var previewRequestBuild: CaptureRequest.Builder? = mCameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
        previewRequestBuild?.addTarget(mSurface!!)
        previewRequestBuild?.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
        var mPreviewRequest = previewRequestBuild?.build()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            var outputs = ArrayList<OutputConfiguration>()
            outputs.add(OutputConfiguration(mSurface!!))
            val sessionConfiguration = SessionConfiguration(
                    SessionConfiguration.SESSION_REGULAR,
                    outputs,
                    { command -> command?.run() },
                    object : CameraCaptureSession.StateCallback() {
                        override fun onConfigured(session: CameraCaptureSession) {
                            mCaptureSession = session
                            mCaptureSession?.setRepeatingRequest(mPreviewRequest!!, null, null)
                        }

                        override fun onConfigureFailed(session: CameraCaptureSession) {

                        }
                    }
            )
            mCameraDevice?.createCaptureSession(sessionConfiguration)
            CameraController.getInstance().openCameraPreview()
        } else {

        }

    }

    override fun initData() {
        VideoEditManager.getInstance()
    }

    override fun onDestroy() {
        super.onDestroy()
        closeCamera()
    }

    private fun closeCamera() {
        if (null != mCaptureSession) {
            mCaptureSession?.close()
            mCaptureSession = null
        }
        if (null != mCameraDevice) {
            mCameraDevice?.close()
            mCameraDevice = null
        }
    }

    override fun ratioCallBack(ratio: Int?) {
        val screenWidth = ScreenUtils.getScreenWidth()
        val screenHeight = ScreenUtils.getScreenHeight()
        println("ratio:$ratio")
        var bottom = 0
        var top = 0
        when(ratio){
            CameraRatioType.RATIO_3_4 ->{
                val height = screenWidth.div(3f / 4f).toInt()
                val value = screenHeight - height
                top = (value * (1f.div(3f))).roundToInt()
                bottom = (value * (2f.div(3f))).roundToInt()
            }
            CameraRatioType.RATIO_9_16 ->{
                val height = screenWidth.div(9f / 16f).roundToInt()
                top = 0
                bottom = screenHeight - height
            }
            CameraRatioType.RATIO_1_1 ->{
                top = (screenHeight - screenWidth).div(2f).roundToInt()
                bottom = top
            }
            CameraRatioType.RATIO_FULL ->{
                top = 0
                bottom = 0
            }
        }
        video_preview_top.setTranslate(top)
        video_preview_bottom.setTranslate(bottom)
    }

    override fun touchTrans() {
        video_preview_func_top.hideRatioPop()
        video_preview_func_top.hideSettingPop()
    }

}